<?php
class Application_Model_UserMapper{
	protected $_dbTable;

	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_User');
		}
		return $this->_dbTable;
	}
	public function save(Application_Model_User $user){
		$data = array(
            'matricule'   => $user->getMatricule() ,
            'nom' => $user->getName(),
            'prenom' => $user->getFirstname(),
            'section_id' => $user->getSection(),
            'annee' => $user->getAnnee(),
            'pseudo' => $user->getLogin(),
            'email' => $user->getEmail(),
		);

		if (null === ($id = $user->getEtudiant_id())) {
			unset($data['id']);
			$this->getDbTable()->insert($data);
			$passDB = new Application_Model_DbTable_UserPasswords();
			$passDB->insert(array(
				'password' 		=> $user->getPassword(),
				'etudiant_id'	=> $this->getDbTable()->getAdapter()->lastInsertId()
			));
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
}